<?php

/**
 * This is the model class for table "gm_users".
 *
 * The followings are the available columns in table 'gm_users':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $fullname
 * @property string $gender
 * @property string $phone
 * @property string $email
 * @property string $address
 * @property integer $birthday
 * @property string $thumb
 * @property string $facebook_id
 * @property string $google_id
 * @property integer $identity_id
 * @property integer $last_login_time
 * @property integer $group
 * @property string $status
 * @property integer $banned_date
 * @property integer $lifted_date
 * @property integer $create_time
 * @property integer $update_time
 */
class UserModel extends CActiveRecord
{
        /**
         * Returns the static model of the specified AR class.
         * @param string $className active record class name.
         * @return UserModel the static model class
         */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
         * @return string the associated database table name
         */
        public function tableName()
        {
            return 'gm_users';
        }

        /**
         * @return array validation rules for model attributes.
         */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('birthday, identity_id, last_login_time, group, banned_date, lifted_date, create_time, update_time', 'numerical', 'integerOnly'=>true),
                array('username', 'length', 'max'=>45),
                array('password, email', 'length', 'max'=>255),
                array('gender', 'length', 'max'=>10),
                array('phone', 'length', 'max'=>20),
                array('status', 'length', 'max'=>30),
                array('fullname, address, thumb, facebook_id, google_id', 'safe'),
                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, username, password, fullname, gender, phone, email, address, birthday, thumb, facebook_id, google_id, identity_id, last_login_time, group, status, banned_date, lifted_date, create_time, update_time', 'safe', 'on'=>'search'),
            );
        }

        /**
         * @return array relational rules.
         */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
            );
        }

        /**
         * @return array customized attribute labels (name=>label)
         */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'username' => 'Username',
                'password' => 'Password',
                'fullname' => 'Fullname',
                'gender' => 'Gender',
                'phone' => 'Phone',
                'email' => 'Email',
                'address' => 'Address',
                'birthday' => 'Birthday',
                'thumb' => 'Thumb',
                'facebook_id' => 'Facebook',
                'google_id' => 'Google',
                'identity_id' => 'Identity',
                'last_login_time' => 'Last Login Time',
                'group' => 'Group',
                'status' => 'Status',
                'banned_date' => 'Banned Date',
                'lifted_date' => 'Lifted Date',
                'create_time' => 'Create Time',
                'update_time' => 'Update Time',
            );
        }

        /**
         * Retrieves a list of models based on the current search/filter conditions.
         * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
         */
        public function search()
        {
            // Warning: Please modify the following code to remove attributes that
            // should not be searched.

            $criteria=new CDbCriteria;

            $criteria->compare('id',$this->id);
            $criteria->compare('username',$this->username,true);
            $criteria->compare('password',$this->password,true);
            $criteria->compare('fullname',$this->fullname,true);
            $criteria->compare('gender',$this->gender,true);
            $criteria->compare('phone',$this->phone,true);
            $criteria->compare('email',$this->email,true);
            $criteria->compare('address',$this->address,true);
            $criteria->compare('birthday',$this->birthday);
            $criteria->compare('thumb',$this->thumb,true);
            $criteria->compare('facebook_id',$this->facebook_id,true);
            $criteria->compare('google_id',$this->google_id,true);
            $criteria->compare('identity_id',$this->identity_id);
            $criteria->compare('last_login_time',$this->last_login_time);
            $criteria->compare('group',$this->group);
            $criteria->compare('status',$this->status,true);
            $criteria->compare('banned_date',$this->banned_date);
            $criteria->compare('lifted_date',$this->lifted_date);
            $criteria->compare('create_time',$this->create_time);
            $criteria->compare('update_time',$this->update_time);

            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
            ));
        }
        
        public function scopes()
        {
            return array(
                'sort_id_desc'=>array(
                    'order'=>'id DESC',
                ),
            );
        }
        
        public function getByCondition($condition_array,$sort_type ='asc'){
            if($sort_type == 'desc' || $sort_type =='DESC'){
                $data = $this->sort_id_desc()->findAllByAttributes($condition_array);
            }
            else {$data = $this->findAllByAttributes($condition_array);}
            
            if(sizeof($data) == 0) return array();
            else{
                $result = array();
                foreach($data as $value){
                    $result[] = $value->attributes;
                }
            }
            return $result;
        }
        
        public function getByID($id){
            $data = $this->findByPk($id);
            if(!is_object($data)){
                return null;
            }else{
                return $data->attributes;
            }
            
        }
        

        public function getByIDs($id_array){
            if(sizeof($id_array) == 0 || $id_array==null){
                return null;
            }
            else{
                $data = array();
                foreach($id_array as $value){
                    $temp = $this->findByPk($value);
                    if(is_object($temp))$data[] = $temp->attributes;
                }
                return $data;
            }
        }
        
        public function getColumnsByCondition($col_array, $condition_array){
            if($col_array == null || sizeof($col_array) == 0){
                return $this->getByCondition($condition_array);
            }
            else{
                $result = array();
                foreach ($col_array as $value){
                    $data = $this->getByCondition($condition_array);
                    foreach($data as $val){
                        $result[$value][$val['id']] = $val[$value];
                    }
                }
                return $result;
            }
        }
        
        public function getAll($sort_type ='asc'){
            if($sort_type =='desc'|| $sort_type == 'DESC'){
                $data = $this->sort_id_desc()->findAll();
            }else{ $data = $this->findAll();}
            
            if(sizeof($data) == 0) throw new CHttpException(404,'The requested page does not exist.');
            else{
                $result = array();
                foreach($data as $value){
                    $result[] = $value->attributes;
                }
            }
            return $result;
        }
        
        public function removeMulti($id_array){
            if(sizeof($id_array) == 0 || $id_array == null){
                return 0;
            }
            else{
                $num_row_deleted = 0;
                foreach($id_array as $value){
                    $data = $this->deleteByPk($value);
                    $num_row_deleted = $num_row_deleted + $data;
                }
                return $num_row_deleted;
            }
        }
        
        public function modify($id,$attributes){
            if(sizeof($attributes) == 0 || $attributes == null){
                return null;
            }
            else{
                $data = $this->findByPk($id);
                if(is_object($data)){
                    foreach($attributes as $key=>$value){
                        $data->setAttribute($key,$value);
                    }
                    $result = $data->save(false);
                    return $result;
                }
                else return null;
            }
        }
 
        public function SearchMultiField($string, $conditions, $page_number, $row_limit, $fields){  
            
            $search_array = explode(' ', $string);
            $criteria=new CDbCriteria;
            
            if($fields == 'all'){
                $fields = array();
                $properties = $this->attributeLabels();
                foreach($properties as $key => $property){
                    $fields[] = $key;
                }
            }
            $criteria->condition = '';
            foreach($conditions as $key=> $condition){
                //$criteria->addSearchCondition($key,$condition,true,'AND');
                $criteria->condition .= " $key='$condition' AND ";
            }
            $criteria->condition .= '(';
            
            foreach($fields as $field){
                foreach($search_array as $search_value){
                    if($search_value != '' && $search_value != null){
                        //$criteria->addSearchCondition($field, "%$search_value%", false,'OR');
                        $criteria->condition .= " $field like '%$search_value%'  or ";
                    }
                }
            }
            $criteria->condition = substr($criteria->condition, 0, -4);
            $criteria->condition .= ')';
            $criteria->limit = $row_limit;
            $criteria->offset = $row_limit*$page_number-$row_limit;
            $result = array();
            $data = $this->findAll($criteria);
            if(is_array($data)){
                foreach($data as $value){
                   $result[] = $value->attributes;
                }
                return $result;
            }else return null;
        }
        
        
        public function countSearch($string,$conditions, $fields){  
            
            $search_array = explode(' ', $string);
            $criteria=new CDbCriteria;
            
            if($fields == 'all'){
                $fields = array();
                $properties = $this->attributeLabels();
                foreach($properties as $key => $property){
                    $fields[] = $key;
                }
            }
            
            foreach($conditions as $key=> $condition){
                //$criteria->addSearchCondition($key,$condition, false,'AND');
                $criteria->condition .= " $key='$condition' AND ";
            }
            $criteria->condition .= '(';
            foreach($fields as $field){
                foreach($search_array as $search_value){
                    if($search_value != '' && $search_value != null){
                        //$criteria->addSearchCondition($field, "%$search_value%", false,'OR');
                        $criteria->condition .= " $field like '%$search_value%'  or ";
                    }
                }
            }
            $criteria->condition = substr($criteria->condition, 0, -4);
            $criteria->condition .= ')';
            return $this->count($criteria);
        }
        
        public function validateFilterVal($filter_value){
            $str_len= strlen ($filter_value);
            if($str_len ==0 || $str_len==null){return false;}
            else{
                for($i=0;$i< $str_len; $i++){
                    if($i == 0 ){
                         if($filter_value{$i} == '<' || $filter_value{$i} == '>' || $filter_value{$i} == '=' || $filter_value{$i} == 'I')return true;
                         //else return false;
                    }else{
                        if($filter_value{$i} == '<' || $filter_value{$i} == '>' || $filter_value{$i} == 'I' || $filter_value{$i} == '=' && $filter_value{$i-1} ==' ')return true;
                        //else return false;
                    }
                }
            }
        }
        
        public function getByPage( $conditions, $page_number, $row_limit, $sort){
            $criteria=new CDbCriteria;
            $criteria->condition = '';
            if($conditions == null || count($conditions) == 0){
                if(is_array($sort)){
                    $criteria->order = "";
                    foreach ($sort as $sort_field => $sort_type){
                        $criteria->order .= "$sort_field $sort_type , ";
                    }
                    $criteria->order = substr($criteria->order, 0, -2);
                }
                $criteria->limit = $row_limit;
                $criteria->offset = $row_limit*$page_number-$row_limit;
                $result = array();
                $data = $this->findAll($criteria); 
                if(is_array($data)){
                    foreach($data as $value){
                        $result[] = $value->attributes;
                     }
                     return $result;
                }else return null;
            }
            else{
                foreach($conditions  as $property => $condition ){
                    if(is_array($condition)){
                        $criteria->condition .= 'AND';
                        $criteria->condition .= '(';
                        foreach($condition as $filter_type => $filter_value){
                            foreach($filter_value as $key => $value){
                                if($this->validateFilterVal($value) == true){
                                    if($key == 0)$criteria->condition .= " $property $value ";
                                    else $criteria->condition .= " $filter_type $property $value ";
                                }
                                else{
                                    if($key == 0)$criteria->condition .= " $property='$value' ";
                                    else $criteria->condition .= " $filter_type $property=$value ";
                                }
                            }
                        }
                        $criteria->condition .= ') ';
                    }
                    else{
                        if($this->validateFilterVal($condition) == true){
                            $criteria->condition .= "AND $property $condition ";
                        }
                        else{
                            $criteria->condition .= "AND $property='$condition' ";
                        }
                    }
                }
                $criteria->condition = substr($criteria->condition, 3, -1);

                if(is_array($sort)){
                    $criteria->order = "";
                    foreach ($sort as $sort_field => $sort_type){
                        $criteria->order .= "$sort_field $sort_type , ";
                    }
                    $criteria->order = substr($criteria->order, 0, -2);
                }

                $criteria->limit = $row_limit;
                $criteria->offset = $row_limit*$page_number-$row_limit;
                $result = array();
                $data = $this->findAll($criteria); 
                if(is_array($data)){
                    foreach($data as $value){
                        $result[] = $value->attributes;
                     }
                     return $result;
                }else return null;
            }
        }
        
        public function countPage($total_row, $limit){
            if($total_row == 0 || $total_row == null)
                return 0;
            else{
                if($total_row % $limit == 0 )return intval($total_row/$limit);
                else return intval($total_row/$limit)+1;
            }
        }
        
        public function countRow( $conditions){
            $criteria=new CDbCriteria;
            $criteria->condition = '';
            if($conditions == null || count($conditions) == 0){
                return $this->count($criteria); 
            }
            else{
                foreach($conditions  as $property => $condition ){
                    if(is_array($condition)){
                        $criteria->condition .= 'AND';
                        $criteria->condition .= '(';
                        foreach($condition as $filter_type => $filter_value){
                            foreach($filter_value as $key => $value){
                                if($this->validateFilterVal($value) == true){
                                    if($key == 0)$criteria->condition .= " $property $value ";
                                    else $criteria->condition .= " $filter_type $property $value ";
                                }
                                else{
                                    if($key == 0)$criteria->condition .= " $property='$value' ";
                                    else $criteria->condition .= " $filter_type $property=$value ";
                                }
                            }
                        }
                        $criteria->condition .= ') ';
                    }
                    else{
                        if($this->validateFilterVal($condition) == true){
                            $criteria->condition .= "AND $property $condition ";
                        }
                        else{
                            $criteria->condition .= "AND $property='$condition' ";
                        }
                    }
                }
                $criteria->condition = substr($criteria->condition, 3, -1);

                return $this->count($criteria); 
 
                }
            }
            
        public function get_start_row($total_row, $page_number, $limit_number){
            if($total_row == 0 || $total_row == null){
                return 0;
            }else{
                $start_row = (($page_number-1)*$limit_number)+1;
                if($start_row > $total_row){
                    $start_row = $total_row;
                }
                return $start_row;
            }
        }
        
        public function get_end_row($total_row, $page_number, $limit_number){
            if($total_row == 0 || $total_row == null){
                return 0;
            }else{
                $end_row = $page_number*$limit_number;
                if($end_row > $total_row){
                    $end_row = $total_row;
                }
                return $end_row;
            }
        }
        
        public function getUnique($field, $sort_type = 'asc'){
            $criteria=new CDbCriteria;
            //$criteria->select = $field;
            $criteria->group = $field;
            $criteria->order = "$field $sort_type";
            $data = $this->findAll($criteria);
            $result = array();
            if(is_array($data)){
                foreach($data as $value){
                    $result[] = $value->attributes;
                }
                return $result;
            }else return  null;
        }
}